import { List, Modal, DatePickerView, Button } from 'antd-mobile-v2';
import * as React from 'react';
import { Props, State } from '../type';
import moment from 'moment';
import './index.less';
import styles from './index.module.less';

const Format = {
  year: 'YYYY',
  month: 'YYYY-MM',
  date: 'YYYY-MM-DD',
  time: 'YYYY-MM-DD HH:mm'
};

export class DatePicker extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();
  constructor(props: any) {
    super(props);
    this.state = {
      showModal: false,
      pickerValue: undefined,
      value: undefined
    };
  }
  componentDidUpdate() {
    if (
      !this.state.showModal &&
      this.props.initValue &&
      this.props.initValue !== this.state.pickerValue
    ) {
      this.setState({
        pickerValue: this.props.initValue
      });
    }
  }
  private showModal = (e: any) => {
    e.preventDefault();
    if (this.props.disabled) return;
    this.setState({
      showModal: true
    });
  };
  onClose = () => {
    this.setState({
      showModal: false
    });
  };
  cancel = () => {
    this.setState({
      showModal: false,
      pickerValue: undefined
    });
  };

  confirm = (fieldProps: any) => {
    const format = this.props.mode ? Format[this.props.mode] : undefined;
    let value = moment(this.state.pickerValue).format(format);
    if (this.props.mode === 'time' && !this.state.pickerValue) {
      const date = new Date();
      const dateStr = date.toLocaleDateString();
      const hour = date.getHours();
      const minute = date.getMinutes() >= 30 ? 30 : '00';
      value = `${dateStr} ${hour}:${minute}`;
    }
    //先触发一次getFieldProps的onChange方法，标记当前表单已经被手动操作过，用于识别表单编辑后路由离开拦截
    if (fieldProps?.onChange) fieldProps?.onChange(value);
    this.props.form &&
      this.props.form.setFieldsValue({ [this.props.code]: value });
    this.props.onChange && this.props.onChange(value);
    this.setState({
      showModal: false
    });
  };
  onChange = (date: any | undefined) => {
    // if (!date) return;
    this.setState({
      pickerValue: date
    });
  };
  modal = (fieldProps: any) => {
    const modeM = this.props.mode === 'time' ? 'datetime' : this.props.mode;
    const format = this.props.mode ? Format[this.props.mode] : undefined;
    const curDate = new Date().toLocaleDateString();
    const hour = new Date().getHours();
    const minute = new Date().getMinutes() >= 30 ? 30 : 0;
    const defaultDate = new Date(curDate + ' ' + hour + ':' + minute);
    return (
      <Modal
        className="datepickerModal"
        visible={this.state.showModal}
        popup
        onClose={this.onClose}
        animationType="slide-up"
        wrapProps={{ onTouchStart: this.onWrapTouchStart }}
      >
        <List
          renderHeader={() => (
            <div className="modalTitle">{this.props.name}</div>
          )}
          renderFooter={() => (
            <div className="modalFooter">
              <Button className="modalButton" onClick={this.cancel}>
                取消
              </Button>
              <Button
                className="modalButton"
                type="primary"
                onClick={() => this.confirm(fieldProps)}
              >
                确定
              </Button>
            </div>
          )}
        >
          <List.Item>
            <DatePickerView
              mode={modeM}
              minDate={
                this.props.minDate
                  ? new Date(this.props.minDate)
                  : new Date('2000/1/1 0:0:0')
              }
              maxDate={
                this.props.maxDate
                  ? new Date(this.props.maxDate)
                  : new Date('2030/1/1 0:0:0')
              }
              format={format}
              minuteStep={modeM === 'datetime' ? 30 : 1}
              value={this.state.pickerValue || defaultDate}
              onChange={this.onChange}
            />
          </List.Item>
        </List>
      </Modal>
    );
  };
  public closest(el: any, selector: any) {
    const matchesSelector =
      el.matches ||
      el.webkitMatchesSelector ||
      el.mozMatchesSelector ||
      el.msMatchesSelector;
    while (el) {
      if (matchesSelector.call(el, selector)) {
        return el;
      }
      el = el.parentElement;
    }
    return null;
  }
  onWrapTouchStart = (e: any) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = this.closest(e.target, '.am-modal-content');
    if (!pNode) {
      e.preventDefault();
    }
  };

  public render() {
    const {
      error,
      form,
      name,
      code,
      mode,
      required,
      // validator,
      ...otherProps
    } = this.props;
    const format = mode ? Format[mode] : undefined;
    // 没有form的话直接取传进来的值，避免反显失败
    const value = form ? form?.getFieldValue(code) : this.props.value;
    const { getFieldProps } = this.props.form || {};

    const extra = value ? (
      moment(value).format(format)
    ) : (
      <span style={{ color: '#B8B8B8' }}>{this.props.placeholder}</span>
    );

    let fieldProps: any = {};

    if (getFieldProps) {
      fieldProps = {
        ...getFieldProps(this.props.code, {
          rules: [{ required: this.props.required, message: `请选择${name}` }]
        })
      };
    }

    return (
      <div className={styles.datePickerContainer}>
        <List.Item
          arrow="horizontal"
          onClick={this.showModal}
          extra={extra}
          {...otherProps}
          className={this.props.disabled ? 'disabled' : ''}
          {...fieldProps}
        >
          {name}
        </List.Item>
        {this.modal(fieldProps)}
      </div>
    );
  }
}
